package ober.toolsimport java.util.Collection;


// 字串連結 closure
def joinStr = { Collection c, String delimiter ->
	StringBuilder builder = new StringBuilder()
	Iterator iter = c.iterator()
	while (iter.hasNext()) {
		builder.append(iter.next())
		if (!iter.hasNext()) {
			break		}
		builder.append(delimiter)	}
	return builder.toString()}
// word 轉成 sql 語法
def word2sql = {	String tableName = 'Token_Customer'
	String word = '''
token_esn	char(16)	TOKEN ESN	V		Vrelated_to	char(23)	TOKEN所關聯的客戶ID或集團戶ID	V		Vis_related _to_group	char(1)	關連對像是否為集團戶0：否，為客戶1：是，為集團戶			'''
	List pks = new ArrayList()	List pLines = new ArrayList()
	String[] lines = word.split('\n')
	for(String line : lines){
		line = line.trim()
		if(line.length() == 0)
			continue
		if(!line.matches(/[a-zA-Z]+.*/))
			continue
		String[] words = line.split('\t')
		String columnName = words[0].trim().replace(' ', '')
		String columnType = words[1].trim()

		boolean ispk = false
		if(words.length >= 4 && words[3] == 'V'){
			pks.add(columnName)
			ispk = true		}

		if(columnType == 'date time')
			columnType = 'datetime'

		boolean isnull = false
		if(words.length >= 5 && words[4] == 'V')
			isnull = true
		pLines << "\t$columnName $columnType ${!isnull ? 'not null' : ''}"	}
	if(pks){		String pkWrods = joinStr(pks, ', ')
		pLines <<  "\tprimary key ($pkWrods)"	}	String result = joinStr(pLines, ' ,\n')	println "create table $tableName ("	println result	println ');'}
// sql 轉成 string buffr 連結
def sql2code = {
	String sql = '''
select c.*
from Customers c
'''

	String[] lines = sql.split('\n')
	for(String line : lines){
		line = line.trim()
		if(line.length() == 0)
			continue
		println "sql.append(\"$line \\n\")"	}}

//word2sql()sql2code()
